package cczxsong;

public class WeightedQU {

    private int[] parent;
    private int[] size;

    public WeightedQU(int n) {
        parent = new int[n];
        size = new int[n];
        for (int i = 0; i < n; i++) {    //设置数组初值
            parent[i] = i;
            size[i] = 1;
        }
    }

    public int find(int p) {//找P的根
        while (p != parent[p])
            p = parent[p];
        return p;
    }

    public boolean connected(int p, int q) {   //连通则p,q的根一样
        return find(p) == find(q);
    }

    public void union(int p, int q) {
        int rootP = find(p);
        int rootQ = find(q);
        if (rootP == rootQ) return;
        // 小树加到大树上
        if (size[rootP] < size[rootQ]) {
            parent[rootP] = rootQ;
            size[rootQ] += size[rootP];
        }
        else {
            parent[rootQ] = rootP;
            size[rootP] += size[rootQ];
        }
    }

    public static void main(String[] args) {
    }

}
